﻿using HackApp.DataAccess;
using System;

namespace HackApp.DataAccess
{
  /// <summary>
  /// Unit of Work implementation using Entity Framework as ORM
  /// </summary>
  public class UnitOfWork : IUnitOfWork, IDisposable
  {
    private HackAppEntities context = new HackAppEntities();

    private IGenericRepository<Idea> ideasRepository;

    public IGenericRepository<Idea> IdeasRepository
    {
        get
        {
            if (this.ideasRepository == null)
            {
                this.ideasRepository = new GenericRepository<Idea>(context);
            }
            return ideasRepository;
        }
    }

    private IGenericRepository<aspnet_Users> userRepository;

    public IGenericRepository<aspnet_Users> UserRepository
    {
      get
      {
        if (this.userRepository == null)
        {
          this.userRepository = new GenericRepository<aspnet_Users>(context);
        }
        return userRepository;
      }
    }

    /// <summary>
    /// Persists chnages to the database
    /// </summary>
    public void Save()  
    {
      context.SaveChanges();
    }

    private bool disposed = false;

    protected virtual void Dispose(bool disposing)
    {
      if (!this.disposed)
      {
        if (disposing)
        {
          context.Dispose();
        }
      }
      this.disposed = true;
    }

    public void Dispose()
    {
      Dispose(true);
      GC.SuppressFinalize(this);
    }
  }
}
